package com.xyz.frame.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xyz.frame.api.service.SzyOssService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

@Service
public class SzyOssServiceImpl implements SzyOssService {

    // 图片类型
    private static String TYPESTR[] = {".png", ".jpg", ".bmp", ".gif", ".jpeg"};

    @Value("${localPath}")
    private String localPath;

    @Override
    public String uploadFileAvatarLocal(MultipartFile file, String profile) {
        // 统一调用生产环境的接口
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://eduback.szytech.com/backapi/api4xyz/eduoss/fileoss?host=cover";

            // 创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 创建请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", file.getResource());

            // 创建HTTP实体
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 发送请求并获取响应
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.parseObject(response.getBody());
            return jsonObject.getString("url");
        } catch (Exception e) {
            e.printStackTrace();
            return "调用生产环境接口失败: " + e.getMessage();
        }
    }
}